from flask import Blueprint, render_template, request, url_for, redirect, flash
from flask_login import login_required, current_user
from ..models import MovieModel
from ..extensions import db

movie_bp = Blueprint(
    'movie_view',
    __name__,
    url_prefix='/',
    template_folder='./templates'
)

@movie_bp.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if not current_user.is_authenticated:
            return redirect(url_for('movie_view.index'))

        title = request.form['title']
        year = request.form['year']

        if not title or not year or len(year) != 4 or len(title) > 60:
            flash('Invalid input.')
            return redirect(url_for('movie_view.index'))

        movie = MovieModel(title=title, year=year)
        db.session.add(movie)
        db.session.commit()
        flash('Item created.')
        return redirect(url_for('movie_view.index'))

    movies = MovieModel.query.all()
    return render_template('index.html', movies=movies)


@movie_bp.route('/movie/edit/<int:movie_id>', methods=['GET', 'POST'])
@login_required
def edit(movie_id):
    movie = MovieModel.query.get_or_404(movie_id)

    if request.method == 'POST':
        title = request.form['title']
        year = request.form['year']

        if not title or not year or len(year) != 4 or len(title) > 60:
            flash('Invalid input.')
            return redirect(url_for('movie_view.edit', movie_id=movie_id))

        movie.title = title
        movie.year = year
        db.session.commit()
        flash('Item updated.')
        return redirect(url_for('movie_view.index'))

    return render_template('edit.html', movie=movie)


@movie_bp.route('/movie/delete/<int:movie_id>', methods=['POST'])
@login_required
def delete(movie_id):
    movie = MovieModel.query.get_or_404(movie_id)
    db.session.delete(movie)
    db.session.commit()
    flash('Item deleted.')
    return redirect(url_for('movie_view.index'))